import React, { useState, useEffect } from "react";
import userImg from "../../assets/icon/unlogin.png";
import userimg from '../../assets/hdpi/user.jpg'
import repImg from "../../assets/icon/common_nav_message_black_n.png";
import backImg from "../../assets/icon/common_icon_back_black_n.png";
import "./index.css";
import { useNavigate } from "react-router-dom";

interface TopNavProps {
  title?: string;
}

interface UserState {
  headPic: string;
  isLoggedIn: boolean;
}

const Index: React.FC<TopNavProps> = ({ title }) => {
  const navigate = useNavigate();
  const [userInfo, setUserInfo] = useState<UserState>({
    headPic: userImg,
    isLoggedIn: false
  });

  useEffect(() => {
    const users = localStorage.getItem("userInfo");
    
    if (users) {
      try {
        const parsedUserInfo = JSON.parse(users);
        setUserInfo({
          headPic: userimg, // 登录后使用固定头像
          isLoggedIn: true,
        });
      } catch (error) {
        // 解析失败，视为未登录
        setUserInfo({
          headPic: userImg,
          isLoggedIn: false,
        });
      }
    } else {
      setUserInfo({
        headPic: userImg,
        isLoggedIn: false,
      });
    }
  }, []);

  const handleUserClick = () => {
    if (userInfo.isLoggedIn) {
      navigate("/user");
    } else {
      navigate("/login");
    }
  };

  return (
    <div className="repository_top">
      <img src={backImg} alt="" onClick={() => navigate(-1)} />
      {title && <div className="title">{title}</div>}
      <div className="rightImg">
        <img 
          src={userInfo.headPic} 
          className="userImg" 
          alt="" 
          onClick={handleUserClick}
        />
        <img src={repImg} className="repImg" alt="" />
      </div>
    </div>
  );
};

export default Index;
